package com.xhs.modular.user.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import com.xhs.common.enums.CommonSortOrderEnum;
import com.xhs.core.message.ReturnResult;
import com.xhs.modular.user.entity.SysUserEntity;
import com.xhs.modular.user.mapper.SysUserMapper;
import com.xhs.modular.user.param.UserPageParam;
import com.xhs.modular.user.service.SysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import static com.mybatisflex.core.query.QueryMethods.noCondition;
import static com.xhs.modular.user.entity.table.SysUserEntityTableDef.SYS_USER_ENTITY;

/**
 * @desc: 系统用户表 服务层实现。
 * @projectName: spring-boot3-demo
 * @author: xhs
 * @date: 2025-06-09 周一 15:15
 */
@Slf4j
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUserEntity> implements SysUserService {

    /**
     * 分页查询用户
     *
     * @param userPageParam 查询条件
     * @return ReturnResult<Object>
     */
    @Override
    public ReturnResult<Object> pageList(UserPageParam userPageParam) {
        Page<SysUserEntity> page = new Page<>(userPageParam.getPageNumber(), userPageParam.getPageSize());
        // 处理排序
        boolean sort = false;
        if (ObjectUtil.isAllNotEmpty(userPageParam.getSortOrder(), userPageParam.getSortField())) {
            CommonSortOrderEnum.validate(userPageParam.getSortOrder());
            sort = true;
        }
        Page<SysUserEntity> entityPage = queryChain()
                .select(SYS_USER_ENTITY.DEFAULT_COLUMNS)
                .from(SYS_USER_ENTITY)
                .where(StringUtils.hasLength(userPageParam.getUserName()) ? SYS_USER_ENTITY.USER_NAME.like(userPageParam.getUserName()) : noCondition())
                .and(StringUtils.hasLength(userPageParam.getJobNumber()) ? SYS_USER_ENTITY.JOB_NUMBER.like(userPageParam.getJobNumber()) : noCondition())
                .and(StringUtils.hasLength(userPageParam.getPhone()) ? SYS_USER_ENTITY.PHONE.like(userPageParam.getPhone()) : noCondition())
                .and(userPageParam.getEmploymentStatus() != null ? SYS_USER_ENTITY.EMPLOYMENT_STATUS.like(userPageParam.getEmploymentStatus()) : noCondition())
                .orderBy(sort ? StrUtil.toUnderlineCase(userPageParam.getSortField()) : "", sort ?
                        userPageParam.getSortOrder().equals(CommonSortOrderEnum.ASC.getValue()) : null)
                .page(page);
        return ReturnResult.success().setData(entityPage);
    }
}
